import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/welcome' })
      NProgress.done()
    } else {
      //判断当前用户是否存在角色
      if (store.getters.roles.length === 0) {
        getInfo(to, next)
      } else {
        next()
      }
    }
  } else {
    // 登录页面放行
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      /* Cookies没有token 去请求地址栏上获取*/
      const searchURL = location.href
      if (
        !searchURL.includes('token') ||
        (searchURL.includes('routerLink') && !hasToken)
      ) {
        //Cookies没有token 并且 地址栏上没有token 代表没登陆
        //跳转到门户网址
        next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
        NProgress.done()
      } else {
        //Cookies没有token 但是 地址栏上有token 需要请求后端获取token对应的用户信息
        let param = searchURL.split('?')[1]
        let token = param.substring(6, param.length)
        //修改vuex的token值
        await store.dispatch('user/saveToken', token)
        getInfo(to, next)
      }
    }
  }
})

const getInfo = (to, next) => {
  store.dispatch('user/getInfo').then(() => {
    store.dispatch('GenerateRoutes').then(accessRoutes => {
      // 根据roles权限生成可访问的路由表
      router.addRoutes(accessRoutes) // 动态添加可访问路由表
      next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
    })
  })
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
